<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="n" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="a" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="g">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="flag ? add() : alter()">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gerDen }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: [{ name: "小王", age: "22", gerDen: "男", id: "1" }],
      id: 0,
      n: "",
      a: "",
      g: "",
      flag: true,
    };
  },
  methods: {
    add() {
      if (this.n !== "" && this.a !== "" && this.g != "") {
        this.id++;
        this.list.push({
          name: this.n,
          age: this.a,
          gerDen: this.g,
        });

        this.n = "";
        this.a = "";
        this.g = "";

        // window.localStorage.setItem("list", JSON.stringify(this.list));
      } else {
        alert("不能为空");
      }
    },
    alter() {
      console.log(1);
      this.list.splice(this.id, 1, {
        name: this.n,
        age: this.a,
        gerDen: this.g,
        id: this.id + 1,
      });
      this.n = "";
      this.a = "";
      this.g = "";
      this.flag = true;
    },
    del(n) {
      this.list.splice(n, 1);
    },
    edit(n) {
      this.n = this.list[n].name;
      this.a = this.list[n].age;
      this.g = this.list[n].gerDen;
      this.flag = false;
      this.id = n;
    },
  },
};
</script>
